package com.tjnu.baiyi.action;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.tjnu.baiyi.entity.TbAlbum;
import com.tjnu.baiyi.entity.TbPhoto;

@Scope("prototype")
@Controller("uploadImageAction")
public class UploadImageAction extends BaseAction {
	private static final long serialVersionUID = 3817302852467556338L;

	/**
	 * 上传图片
	 * 
	 * @return
	 * @throws Exception
	 */
	public String upload() throws Exception {
		try {
			System.out.println("UploadImageAction.upload()");
			// 获取从前台页面传过来的上传的图片所属的相册Id，并求该相册的具体内容
			album = tbAlbumDao.findById(Integer.parseInt(id));
			// 得到物理路径
			String realPath = ServletActionContext.getServletContext()
					.getRealPath("/");
			// 创建该路径
			File path = new File(realPath);
			// 判断是否存在该路径，如果不存在，创建之
			if (!path.exists()) {
				path.mkdirs();
			}
			// 更改要上传的文件的名称
			for (int i = 0; i < imageFileName.length; i++) {
				String name = imageFileName[i].substring(0,
						imageFileName[i].lastIndexOf("."));
				String imageType = imageFileName[i].substring(imageFileName[i]
						.lastIndexOf("."));// 实际中不能根据文件名判断。需要读取ContentType和文件头信息。
				UUID uuid = UUID.randomUUID();
				String s = uuid.toString().replace("-", "").toUpperCase();

				imageFileName[i] = "uploadimage/" + name + s + imageType;
			}
			// 将多个文件写到服务器硬盘
			for (int i = 0; i < image.length; i++) {
				File file = new File(path, imageFileName[i]);
				FileUtils.copyFile(image[i], file);
				// 更改要上传的文件的名称
				imageFileName[i] = "../" + imageFileName[i];
				TbPhoto photo = new TbPhoto(album, imageFileName[i],
						imageFileName[i]);
				tbPhotoDao.save(photo);// 把图片信息
			}
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}

	}

	// 添加商品的主要信息
	private File[] image;
	private String[] imageFileName;
	private String[] imageContentType;
	private String id;

	public File[] getImage() {
		return image;
	}

	public void setImage(File[] image) {
		this.image = image;
	}

	public String[] getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String[] imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String[] getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String[] imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
}
